import { createRouter, createWebHistory } from "vue-router";
import { ElMessage } from "element-plus";

export const menu_router = [
  {
    path: "/",
    name: "home",
    meta: {
      title: "首页",
    },
    component: () => import("../views/home/indexView.vue"),
  },
  {
    path: "/list",
    name: "list",
    meta: {
      title: "列表",
    },
    component: () => import("../views/list/indexView.vue"),
  },
  {
    path: "/customer",
    name: "customer",
    meta: {
      title: "客服聊天",
    },
    component: () => import("../views/customer/indexView.vue"),
  },
  {
    path: "/echartspage",
    name: "echartspage",
    meta: {
      title: "图表",
      roles: ["admin"],
    },
    component: () => import("../views/echartspage/indexView.vue"),
  },
  {
    path: "/map",
    name: "map",
    meta: {
      title: "地图",
    },
    children: [
      {
        path: "/map/map1",
        name: "map1",
        meta: {
          title: "地图1",
        },
        component: () => import("../views/map1/indexView.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "layout",
      component: () => import("../views/layout/indexView.vue"),
      children: menu_router,
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/login/indexView.vue"),
    },
    {
      path: "/403",
      name: "403",
      component: () => import("../views/403/indexView.vue"),
    },
    {
      path: "/404",
      name: "404",
      component: () => import("../views/404/indexView.vue"),
    },
    // {
    //   path: "/:pathMatch(.*)*",
    //   name: "404",
    //   component: () => import("../views/404/indexView.vue"),
    // },
    {
      path: "/:pathMatch(.*)*",
      redirect: "/404",
    },
  ],
});

router.beforeEach((to, from, next) => {
  // 判断用户是否登录，根据accessToken
  const accessToken = localStorage.getItem("accessToken");
  if (!accessToken) {
    if (to.path === "/login") {
      next();
    } else {
      ElMessage({
        message: "请重新登陆",
        type: "warning",
      });
      next("/login");
    }
  } else {
    if (to.path === "/login") {
      next("/");
    }
    // 路由权限
    if (
      to.meta.roles &&
      !to.meta.roles.includes(localStorage.getItem("role"))
    ) {
      next("/403");
    }
  }
  next();
});
export default router;
